import NProgress from 'nprogress' // 实现加载页面时有进度条的效果
import 'nprogress/nprogress.css' // progress bar style
import router, { syncRouters } from './router'
import store from './store'
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  if (token) {
    NProgress.start()
    if (to.path === '/login') {
      NProgress.done()
      next('/')
    } else {
      // 如果本地没有用户信息就再次发送请求
      if (!store.getters.userId) {
        const res = await store.dispatch('user/getProfile')
        // console.log(res.roles.menus)
        const menuList = res.roles.menus
        // console.log(menuList)
        const filterRouter = syncRouters.filter(item => menuList.includes(item.children[0].name))
        // console.log(filterRouter)
        // 添加动态路由 这里知识补充了路由配置不会渲染导侧边栏
        router.addRoutes(filterRouter)
        filterRouter.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('menus/updateMenuList', filterRouter)

        // 解决刷新出现的白屏bug
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach(() => {
  // 页面跳转后执行
  NProgress.done()
})
